<template>
    <uni-loading v-if="loading"></uni-loading>
    <view class="body" v-else>
        <!--  顶部  -->
        <top-tab :options="stockList" :locationName="locationName" @stockChange="stockChange"
            @handleBarnChoose="handleBarnChoose"></top-tab>
        <!--  列表  -->
        <template v-if="purchaseList && purchaseList.length > 0">
            <uni-swipe-action>
                <uni-swipe-action-item :left-options="options" v-for="(item, index) in purchaseList"
                    @click="handleDelete(item)">
                    <view class="panel" @click="openDetail(item)">
                        <view class="panel_title">
                            <view class="panel_title_left">{{ item.materialName }}</view>
                        </view>
                        <view class="panel_content">
                            <view class="panel_content_row">
                                <view class="panel_content_row_item">
                                    <view class="panel_content_row_item_title">批次：</view>
                                    <view class="panel_content_row_item_value">{{ item.batchNo }}</view>
                                </view>
                                <view class="panel_content_row_item">
                                    <view class="panel_content_row_item_title">仓位：</view>
                                    <view class="panel_content_row_item_value">{{ item.locationNo }}</view>
                                </view>
                            </view>
                            <view class="panel_content_row">
                                <view class="panel_content_row_item">
                                    <view class="panel_content_row_item_title">已入库：</view>
                                    <view class="panel_content_row_item_value">{{ item.count }}{{ item.unit }}</view>
                                </view>
                                <view class="panel_content_row_item">
                                    <view class="panel_content_row_item_title">剩余：</view>
                                    <view class="panel_content_row_item_value">
                                        {{ item.nowColCount - item.count }}{{ item.unit }}
                                    </view>
                                </view>
                                <view class="panel_content_row_item">
                                    <view class="panel_content_row_item_title">总重：</view>
                                    <view class="panel_content_row_item_value">{{ item.nowColCount }}{{ item.unit }}
                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="panel_dashboard">
                            <view class="panel_dashboard_item">
                                <view class="panel_dashboard_item_number success">{{ item.boxCount }}</view>
                                <view class="panel_dashboard_item_value">已入库</view>
                            </view>
                            <view class="panel_dashboard_item">
                                <view class="panel_dashboard_item_number error">
                                    {{ item.nowColBoxCount - item.boxCount }}
                                </view>
                                <view class="panel_dashboard_item_value">剩余</view>
                            </view>
                            <view class="panel_dashboard_item">
                                <view class="panel_dashboard_item_number default">{{ item.nowColBoxCount }}</view>
                                <view class="panel_dashboard_item_value">总数</view>
                            </view>
                        </view>
                    </view>
                </uni-swipe-action-item>
            </uni-swipe-action>
        </template>
        <uni-empty-info v-else label="暂无物料信息"></uni-empty-info>

        <!--  底部按钮  -->
        <view class="footerPanel">
            <view class="footerPanel_body">
				<button @click="handleWarehousing" class="footerBtn save"><i
				        class="iconfont icon-duihao btn_icon"></i>立即入库
				</button>
                <button @click="handleScanCode" class="footerBtn scan" type="primary"><i
                        class="iconfont icon-saomiao btn_icon"></i>扫码
                </button>
            </view>
        </view>

        <!--  操作面板  -->
        <min-action-sheet ref="as"></min-action-sheet>

        <!-- 弹出层 -->
        <MaterialPopupThin ref="materialPopupThinRef" title="物料扫描" type="finished" @scanSuccess="handleScanSuccess"
            @success="addUserAllocationBoxList">
        </MaterialPopupThin>

        <BarnPopup ref="barnPopup" @confirm="onLocationChange"></BarnPopup>

        <!-- 详情 -->
        <Detail ref="detailRef" @delete="deleteMaterialBox" @deleteTraceBack="deleteBoxTraceBack"></Detail>
    </view>
</template>
<script>
    import topTab from "@/components/top-tab/top-tab"
    import minActionSheet from '@/components/min-action-sheet/min-action-sheet'
    import uniLoading from "../../vBase/components/uni-loading/uni-loading"
    import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
    import MaterialPopupThin from "@/components/popup/materialPopupThin"
    import BarnPopup from "@/components/popup/barnPopup"
    import Detail from "../pop/detail-material.vue"

    export default {
        components: {
            topTab,
            minActionSheet,
            uniLoading,
            uniEmptyInfo,
            MaterialPopupThin,
            BarnPopup,
            Detail
        },
        data() {
            return {
                loading: false,
                purchaseList: [],
                options: [{
                    text: '删除',
                    style: {
                        backgroundColor: '#FF4E74'
                    }
                }],
                scaningShow: false,
                scanNo: null,
                isFouce: false,
                stockList: [],
                stockNo: '',
                locationNo: '',
                locationName: '',
                orderNo: '',
                billNo: '',
                supplierNo: '',
                supplierName: '',
            }
        },
        async onLoad(e) {
            if (e?.orderNo) this.orderNo = e.orderNo
            if (e?.billNo) this.billNo = e.billNo
            await this.getStockList();
            this.initData()
        },
        methods: {
			/**
			 * 删除箱子
			 * @param {Object} id
			 */
			deleteMaterialBox(e) {
				let {
					material,
					success
				} = e
				let self = this
				self.$api.deletePurinMaterialBox({
					billNo: this.billNo,
					id: material.id
				}, {
					loading: true
				}).then((res) => {
					if (!res.res) return;
					self.initData();
					success && success();
				});
			},
			
            /** 查询仓库*/
            async getStockList() {
                this.loading = true;
                try {
                    let {
                        res,
                        stockList = []
                    } = await this.$api.getCustomerStock();
                    if (!res) return;
                    this.stockList = stockList;
                    if (stockList.length) this.stockNo = stockList[0].stockNo;
                } finally {
                    this.loading = false;
                }
            },
            /** 初始化数据 */
            initData() {
                if (!this.stockNo) return;
                this.pageConfig = {
                    pageIndex: 0,
                    pageSize: 20,
                    bottomEnd: false,
                    bottomLoading: true
                }
                this.getPurchaseList()
            },

            /**
             * 查看详情
             */
            async openDetail(material) {
                const {
                    id,
                    stockNo,
                    batchNo,
                    materialName,
                    materialNo,
					billNo
                } = material
                let {
                    res,
                    data = []
                } = await this.$api.getUserPurInMaterialBox({
                    id,
                    stockNo,
					billNo: billNo
                }, {
                    loading: true
                });
                let param = {
                    title: '入库明细',
                    dataList: data,
                    type: null,
                    errorList: []
                }
                this.$refs.detailRef.open(param)
            },

            /** 获取数据 */
            async getPurchaseList() {
                let {
                    res,
                    data = []
                } = await this.$api.getUserPurInMaterial({
                    stockNo: this.stockNo,
                    isBc: true,
                    orderNo: this.orderNo,
					billNo: this.billNo
                });
                if (!res) return;
                this.purchaseList = data;
                this.loading = false;
                this.pageConfig.bottomEnd = true;
                this.pageConfig.bottomLoading = false;
                uni.stopPullDownRefresh();
            },

            /** 选择仓位*/
            onLocationChange(location) {
                this.locationNo = location.locationNo;
                this.locationName = location.locationName;
            },

            /**
             * 删除箱子
             * @param {Object} id
             */
            deleteMaterialBox(e) {
                let {
                    material,
                    success
                } = e
                let self = this
                self.$api.deletePurinMaterialBox({
                    id: material.id,
					billNo: this.billNo
                }, {
                    loading: true
                }).then((res) => {
                    if (!res.res) return;
                    self.initData();
                    success && success();
                });
            },
			
			/**
			 * 跳转至
			 */
			goto() {
				if (!this.orderNo) return
				this.$navigateTo('/pages/purchase/packageOrderList?orderNo=' + this.orderNo)
			},

            // /**
            //  * 
            //  * @param {Object} e
            //  */
            // bindEditCount(e, v) {
            //  let count = e.detail.value ? Number(e.detail.value) : 0
            //  v.count = count
            // },

            /**
             * 扫码成功
             */
            async handleScanSuccess(e) {
                try {
                    let param = typeof e === 'string' ? {
                        boxNo: e
                    } : {
                        rfid: e
                    }

                    let api = typeof e === 'string' ? "getMaterialByBox" : "getMaterialByRfid"
                    let res = await this.$api[api](param)
                    if (!res.res) return
                    this.materialList = res.hasOwnProperty('data') ? res.data : [res] ?? []
                    // 直接调用添加接口
                    if (this.materialList && this.materialList.length) {
                        this.addUserAllocationBoxList(this.materialList)
                    } else {
                        uni.showToast({
                            title: "未查询到物料信息",
                            icon: "none"
                        })
                        this.handleMediaPlayer('error')
                    }
                } catch (e) {
                    this.handleMediaPlayer('error')
                }
            },

            /**
             * 添加箱子
             * @param {Object} e
             */
            async addUserAllocationBoxList(e) {
                try {
                    const res = await this.$api.addUserPurinMaterialBoxList({
                        stockNo: this.stockNo,
                        locationNo: this.locationNo,
                        boxList: e,
                        isBc: true,
                        orderNo: this.orderNo,
						billNo: this.billNo
                    })
                    uni.showToast({
                        title: "添加成功",
                        icon: "none"
                    })
                    this.handleMediaPlayer('success')
                } catch (e) {
                    // 添加的时候可能会有重复的情况，箱号已入库有共同的提示，所以这个排除这个情况
                    if (e?.data?.err && "箱号已入库!" !== e?.data?.err) {
                        this.handleMediaPlayer('error')
                    }
                } finally {
                    this.initData()
                }
            },

            /** 立即入库 */
            handleWarehousing() {
            	const {
            		stockNo,
            		locationNo,
            		purchaseList
            	} = this;
            	if (!stockNo) {
            		uni.showToast({
            			title: '请选择仓库',
            			icon: 'none'
            		});
            		return;
            	}
            	if (!purchaseList || !purchaseList.length) {
            		uni.showToast({
            			title: '请扫码添加物料',
            			icon: 'none'
            		});
            		return;
            	}
            	const self = this
            	uni.showModal({
            		title: '提示',
            		content: '是否立即入库？',
            		success(res) {
            			if (res.confirm) {
            				self.$api.auditPurinOrder({
            					stockNo: self.stockNo,
            					source: 'PDA',
								isBc: true,
								orderNo: self.orderNo,
								billNo: self.billNo
            				}).then(res => {
            					if (res.res) {
            						uni.showToast({
            							title: '入库成功',
            							icon: 'none'
            						})
            						setTimeout(() => {
										uni.navigateBack()
									}, 500)
            					}
            				})
            			}
            		}
            	})
            },
            
            /**
             * 选择仓库
             * @param e
             */
            stockChange(e) {
                this.stockNo = this.stockList[e].stockNo
                this.initData()
            },

            // /**
            //  * 选择仓位
            //  * @param e
            //  */
            // stockLocation(e) {
            //  this.locationNo = e.locationNo
            //  this.locationName = e.locationName
            // },

            /**
             * 选择
             */
            handleBarnChoose() {
                this.$refs.barnPopup.open(this.stockNo);
            },

            /** 扫码 */
            async handleScanCode() {
                if (!this.locationNo) {
                    uni.showToast({
                        title: "请选择仓位",
                        icon: "none"
                    })
                    return
                }
                this.$refs.materialPopupThinRef.open()
            },

            /**
             * 删除物料
             * @param {Object} e
             */
            handleDelete(material) {
				console.log("material", material);
                const self = this
                uni.showModal({
                    title: '提示',
                    content: '是否删除物料？',
                    success(res) {
                        if (res.confirm) {
                            self.$api.deletePurinMaterial({
                                id: material.id
                            }, {
                                loading: true
                            }).then(res => {
                                if (res.res) {
                                    uni.showToast({
                                        title: '物料删除成功',
                                        icon: 'none'
                                    })
                                    self.initData();
                                }
                            })
                        }
                    }
                })
            },

            /**
             * 下拉刷新数据
             */
            onPullDownRefresh() {
                this.initData()
            },

            /** 上滑加载 */
            onReachBottom() {
                if (!this.pageConfig.bottomEnd) {
                    this.pageConfig.pageIndex++
                    this.pageConfig.bottomLoading = true
                    this.getPurchaseList();
                }
            },
        }
    }
</script>
<style lang="scss" scoped>
    @import "../../static/css/common";
</style>
